package com.joysuch.wwyt.patrol.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.joysuch.wwyt.bp.entity.BPNFCLocation;
import com.joysuch.wwyt.bp.repository.BPNFCLocationDao;
import com.joysuch.wwyt.bp.service.BpNFCLocationService;
import com.joysuch.wwyt.core.bean.BaseNfcCardBean;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.common.util.DateTimeUtil;
import com.joysuch.wwyt.core.exception.ApiBusinessException;
import com.joysuch.wwyt.core.support.Context;
import com.joysuch.wwyt.patrol.entity.PatrolCheckPoint;
import com.joysuch.wwyt.patrol.entity.bean.PatrolCheckPointBean;
import com.joysuch.wwyt.patrol.entity.bean.SimpleListDataType;
import com.joysuch.wwyt.patrol.entity.dto.AppCheckPointDto;
import com.joysuch.wwyt.patrol.entity.vo.CheckPointDetailVo;
import com.joysuch.wwyt.patrol.entity.vo.CheckPointListVo;
import com.joysuch.wwyt.patrol.mapper.PatrolTaskMapper;
import com.joysuch.wwyt.patrol.service.PatrolCheckPointService;
import com.joysuch.wwyt.workflow.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zr
 * @since 2022-02-28
 */
@RestController
@RequestMapping("/patrol/patrol-check-point")
@Api(tags = "智能巡检-检查点信息")
public class PatrolCheckPointController {

    @Autowired
    private PatrolCheckPointService patrolCheckPointService;
    @Autowired
    private BPNFCLocationDao bpnfcLocationDao;

    @PostMapping("/saveCheckPoint")
    @ApiOperation("保存检查点信息")
    @RequiresPermissions("patrol:patrol-check-point:saveCheckPoint")
    public ResultBean saveCheckPoint(@RequestBody PatrolCheckPointBean bean){
        try {
            patrolCheckPointService.saveCheckPoint(bean);
            return ResultBean.defaultSuccessResult();
        } catch (ApiBusinessException e) {
            e.printStackTrace();
            return ResultBean.fail(e.getCode(),e.getMessage());
        }
    }

    @PostMapping("/updateCheckPoint")
    @ApiOperation("修改检查点信息")
    @RequiresPermissions("patrol:patrol-check-point:updateCheckPoint")
    public ResultBean updateCheckPoint(@RequestBody PatrolCheckPointBean bean){
        try {
            patrolCheckPointService.updateCheckPoint(bean);
            return ResultBean.defaultSuccessResult();
        } catch (ApiBusinessException e) {
            return ResultBean.fail(e.getCode(),e.getMessage());
        }
    }

    @GetMapping("/findListForPage")
    @ApiOperation("检查点分页")
    public ResultBean findListForPage(Integer page , Integer size , Long areaId , Long typeId , String pointName){
        return patrolCheckPointService.findListForPage(page+1,size,areaId,typeId,pointName);
    }

    @GetMapping("/getPointById")
    @ApiOperation("根据检查点id获取检查点详情")
    public ResultBean getPointById(Long id){
        CheckPointDetailVo checkPointDetailVo = patrolCheckPointService.getPointById(id);
        return ResultBean.success(checkPointDetailVo);
    }

    @GetMapping("/getPointList")
    @ApiOperation("获取检查点列表")
    public ResultBean getPointList(){
        List<CheckPointListVo> checkPointListVoList = patrolCheckPointService.getPointList();
        return ResultBean.success(checkPointListVoList);
    }

    @GetMapping("/deletePointById")
    @ApiOperation("根据id删除检查点")
    @RequiresPermissions("patrol:patrol-check-point:deletePointById")
    public ResultBean deletePointById(Long id , Integer skipFlag){
        return patrolCheckPointService.deletePointById(id,skipFlag);
    }

    @GetMapping("/getDataType")
    @ApiOperation("获取数据类型下拉列表")
    public ResultBean getSimpleListDataType(String flag){
        List<SimpleListDataType> dataTypeList =  patrolCheckPointService.getSimpleListDataType(flag);
        return ResultBean.success(dataTypeList);
    }

    @GetMapping("/getCheckPoint")
    @ApiOperation("APP做任务时根据检查点id获取检查项目信息")
    public ResultBean getCheckPointByPointIdForApp(Long pointId){
        CheckPointDetailVo checkPointByPlanIdForApp = patrolCheckPointService.getCheckPointByPointIdForApp(pointId);
        return ResultBean.success(checkPointByPlanIdForApp);
    }

    @GetMapping("/exportCheckItemTem")
    @ApiOperation("导出检查项目模板")
    public ResultBean ExportCheckItemTem(HttpServletResponse response){

        try {
            XSSFWorkbook workBook = patrolCheckPointService.exportCheckItemTem();
            ServletOutputStream outputStream = response.getOutputStream();
            String name = "检查项目导入模板.xlsx";
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(name, "UTF-8"));
            workBook.write(outputStream);
            outputStream.close();
            return ResultBean.success("下载成功...... ");
        } catch (IOException e) {
            e.printStackTrace();
            return ResultBean.fail(101, "下载失败:" + e.getMessage());
        }
    }

    @GetMapping("/exportCheckItemData")
    @ApiOperation("导出检查点下的检查项目")
    public ResultBean ExportCheckItemData(HttpServletResponse response,Long pointId){
        String pointName = patrolCheckPointService.findNameById(pointId);
        if (StringUtils.isBlank(pointName)){
            return ResultBean.fail(101,"下载失败: 该检查点不存在");
        }
        try {
            XSSFWorkbook workBook = patrolCheckPointService.exportCheckItemData(pointId);
            ServletOutputStream outputStream = response.getOutputStream();
            String name = pointName + "检查项目.xlsx";
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(name, "UTF-8"));
            workBook.write(outputStream);
            outputStream.close();
            return ResultBean.success("下载成功...... ");
        } catch (IOException e) {
            e.printStackTrace();
            return ResultBean.fail(101, "下载失败:" + e.getMessage());
        }
    }

    @Autowired
    private BpNFCLocationService bpNFCLocationService;
    @Autowired
    private PatrolTaskMapper patrolTaskMapper;


    @GetMapping("/searchTaskByPointId")
    @ApiOperation("根据nfc卡号找出对应任务")
    public ResultBean searchTaskByPointId(String code){
        if (StringUtils.isEmpty(code)) {
            return ResultBean.fail(1002, "未扫到nfc卡");
        }
        BPNFCLocation card = bpnfcLocationDao.findFirstByCode(code);
        if (card == null) {
            return ResultBean.fail(1002, "NFC未关联检查点");
        }
        BaseNfcCardBean nfcCardBean = new BaseNfcCardBean();
        nfcCardBean.setId(card.getId());
        nfcCardBean.setCode(card.getCode());
        nfcCardBean.setName(card.getName());

        List<PatrolCheckPoint> checkPoints = patrolCheckPointService.list(new LambdaQueryWrapper<PatrolCheckPoint>()
                .eq(PatrolCheckPoint::getNfc, code)
                .eq(PatrolCheckPoint::getDeleteFlag, "0")
                .eq(PatrolCheckPoint::getTenentId, Context.getCurrentTenantId()));

        if (CollectionUtils.isEmpty(checkPoints)) {
            return ResultBean.fail(1002, "NFC未关联检查点");
        }
        List<AppCheckPointDto> appCheckPointDtos = patrolTaskMapper.selectCheckPointByNfcCode(code, Context.getCurrentUser().getRealUserId());
        appCheckPointDtos = appCheckPointDtos.stream().filter(e -> "待完成".equals(e.getStatus())).collect(Collectors.toList());

        if (appCheckPointDtos.size() == 0) {
            return ResultBean.fail(1002, "此检查点当前时间没有任务");
        }

        appCheckPointDtos.forEach(dto -> {
            if (dto.getEndTime().getTime() - dto.getStartTime().getTime() >= 24L * 3600 * 1000) {
                String endTime = DateTimeUtil.formatDate(dto.getEndTime(), "yyyy/MM/dd");
                String startTime = DateTimeUtil.formatDate(dto.getStartTime(), "yyyy/MM/dd");
                dto.setShowTime(startTime + "-" + endTime);
            } else {
                String endTime = DateTimeUtil.formatDate(dto.getEndTime(), "yyyy/MM/dd HH:mm:ss");
                String startTime = DateTimeUtil.formatDate(dto.getStartTime(), "yyyy/MM/dd HH:mm:ss");
                String startDay = startTime.substring(0, 10);
                String endDay = endTime.substring(0, 10);

                if (startDay.equals(endDay)) {
                    String[] sItems = startTime.split(" ");
                    String sStr = sItems[1].substring(0, 5);
                    String[] eItems = endTime.split(" ");
                    String eStr = eItems[1].substring(0, 5);
                    dto.setShowTime(sStr + "-" + eStr);
                } else {
                    dto.setShowTime(startTime + "-" + endTime);
                }
            }
        });

        return ResultBean.success(appCheckPointDtos);
    }
}

